<template>
  <div class="rightBodyContent">
    <div class="rightBodyContent-in">
      <div class="hearder-search">
        <div class="toplineBox mb-10">
          <div class="toplineBox-left">
            <el-input v-model="eidtFrom.vote_name" placeholder="填写投票标题" size="small" class="w-140 mr-10"></el-input>
            <el-select v-model="eidtFrom.is_vote" placeholder="选择状态" size="small" class="w-140 mr-10">
              <el-option :label="item.name" :value="item.id" v-for="(item, index) in sectionList"
                         :key="index"></el-option>
            </el-select>
            <el-button type="primary" size="small" @click="searchFn"><i class="el-icon-search"></i>搜索</el-button>
            <el-button size="small" @click="refreshFn"><i class="el-icon-refresh"></i>刷新</el-button>
          </div>
          <p class="numberline toplineBox-right">总{{page.total}}条</p>
        </div>
      </div>
      <!--本体列表，数据 -->
      <div class="table-body">
        <div class="table-body-box">
          <el-table
                  ref="multipleTable"
                  :data="arryList"
                  :stripe="tableStripe"
                  :border="tableBorder"
                  tooltip-effect="dark"
                  style="width: 100%"
                  header-cell-class-name="table-text-c"
                  cell-class-name="table-text-c">
            <el-table-column
                prop="id"
                label="ID"
            width="80">
            </el-table-column>
            <el-table-column
                    prop="vote_name"
                    label="投票事项">
            </el-table-column>
            <el-table-column
                    label="发起人"
                    width="140">
              <template slot-scope="scope">
                {{scope.row.user?scope.row.user.realname:''}}
              </template>
            </el-table-column>
            <el-table-column
                    label="参加人员">
              <template slot-scope="scope">
                <span class="tablelineUser">{{scope.row.username}}</span>
                <el-popover
                        placement="left-start"
                        :title="scope.row.popovertitle"
                        width="220"
                        trigger="hover">
                  <div class="tableline" v-if="scope.row.users.length">
                    <p class="list" v-for="(item,index) in scope.row.users" :key="index">
                      <span>{{item.realname}}</span>
                    </p>
                  </div>
                  <span slot="reference" class="tablelineBtn">{{scope.row.others_link_str}}</span>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column
                    prop="start_time"
                    label="通知时间"
                    width="110">
            </el-table-column>
            <el-table-column
                    prop="end_time"
                    label="结束时间"
                    width="110">
            </el-table-column>
            <!--排序-->
            <el-table-column
                    key="1"
                    label="状态"
                    width="70">
              <template slot-scope="scope">
                <div v-if="scope.row.btnstate">
                  <span v-if="scope.row.status==1" class="canborrow">已投</span>
                  <span v-else>
                    <span v-if="scope.row.is_outTime" class="notborrow">未投</span>
                    <span v-else class="notborrow">已过期</span>
                  </span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="220">
              <template slot-scope="scope">
                <div style="display: flex;align-items: center;justify-content: center;">
                  <el-button size="small" @click="handleEdit(scope.$index,1)">投票详情</el-button>
                  <div v-if="scope.row.status==0&&scope.row.is_outTime">
                    <el-button type="warning" v-if="scope.row.status==0&&scope.row.btnstate" size="small"
                               @click="handleEdit(scope.$index,2)">参与投票
                    </el-button>
                  </div>
                  <el-button type="danger" size="small" @click="handleDetel(scope.$index)" v-if="userInfo.id==1">
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!--工具条 分页-->
      <el-col :span="24" class="toolbar">
        <el-pagination
            background
            :page-size="page.pagesize"
            :current-page="page.pageindex"
            layout="total, prev, pager, next"
            :total="page.total"
            @current-change="handleSizeChange"></el-pagination>
      </el-col>
      <!--成功提示-->
      <editvote :visible.sync="editFormVisible" @initFile="initFile" :eidtId="eidtId" :pageType="pageType"></editvote>
    </div>
  </div>
</template>

<script>
  import {pagination, tableoption, dayCheck} from '@/utils/util.js'
  import editvote from '@/components/dialog/editvote.vue'
  import api from '@/utils/api.js'
  import {mapGetters} from "vuex";

  export default {
    components: {
      editvote
    },
    data () {
      return {
        tableStripe: true, // 是否斑马栏
        tableBorder: true, // 单元格右边边框
        searchWord: '', // 搜索名称
        editLoading: false, // 编辑界面按键缓存
        editFormStatus: true,
        editForm: {}, // 编辑界面数据
        addLoading: false,
        detailVisible: false, // 编辑界面是否显示
        arryList: null, // 数据列表
        pageTotal: 0, // 总页数
        newObj: [],
        radioName: 0,
        tieleName: '',
        handleSelection: null, // checked选中框
        flag: true,
        tableStyle: tableoption,
        // 设置table页面分页所需
        page: {
          pageindex: pagination.pageIndex,
          pagesize: pagination.pageSize,
          total: pagination.total
        },
        eidtFrom: {
          is_vote: '',
          vote_name: '',
          p: 1
        },
        sectionList: [
          {
            name: '全部',
            id: ''
          },
          {
            name: '已投',
            id: 1
          },
          {
            name: '未投',
            id: 0
          }
        ],
        editFormVisible: false, // 弹窗
        pageType: null,
        eidtId: null,
      }
    },
    computed: {
      ...mapGetters(['userInfo']),
    },
    created () {
      this.InitFn()
    },
    methods: {
      // 初始化
      InitFn () {
        let option = JSON.parse(JSON.stringify(this.eidtFrom))
        option.p = this.page.pageindex
        this.$fetch(api.vote_index, option).then((response) => {
          if (response.code === 0) {
            for (let item of response.list.data) {
              let userName = []
              let btnstate = false
              for (let n in item.users) {
                if (Number(this.userInfo.id) === Number(item.users[n].id)) {
                  btnstate = true
                }
                if (n < 3) {
                  userName.push(item.users[n].realname)
                }
              }
              item.is_outTime = dayCheck(item.end_time)
              item.btnstate = btnstate
              item.others_link_str = '共' + item.users.length + '位参与人员'
              item.username = userName.join(',')
              if (item.users.length > 3) {
                item.username += ' 等'
              }
              item.popovertitle = '其他参与人（' + item.users.length + '人）'
              item.start_time = item.start_time.split(' ')[0]
              item.end_time = item.end_time.split(' ')[0]
            }
            this.arryList = response.list.data
            this.page.total = response.list.total
          } else {
          }
        }).catch((err) => {
          console.log(err)
        })
      },
      searchFn () {
        this.page.pageindex = 1
        this.InitFn()
      },
      // 分页
      handleSizeChange (val) {
        this.page.pageindex = val
        this.InitFn()
      },
      handleSelectionChange (val) {
        console.log(val) // 所有选中值
        this.handleSelection = val
      },
      // 编辑
      handleEdit (index, option) {
        this.eidtId = this.arryList[index].id
        this.pageType = option
        this.editFormVisible = true
        return false
        let option_ = row.option
        let newObj = []
        for (let i = 0; i < option_.length; i++) {
          let name_ = option_[i].split(':')
          newObj.push(name_[0])
        }
        this.newObj = newObj
        this.editFormStatus = true
        this.$post('vote/edit/id/' + row.id, {}).then((response) => {
          if (response.code === 0) {
            let rowlist = response.vo.option
            if (typeof rowlist !== 'string') {
              response.vo.option = response.vo.option.join(', ')
            }
            this.editForm = response.vo
            this.detailVisible = true
          } else {
          }
        }).catch((err) => {
          console.log(err)
        })
      },
      // 编辑
      openBorrwBook (index, row) {
        // 切割数据
        let option_ = row.option
        let newObj = []
        for (let i = 0; i < option_.length; i++) {
          let name_ = option_[i].split(':')
          newObj.push(name_[0])
        }
        this.newObj = newObj
        console.log('选项数据选项：', newObj)
        this.radioName = 0
        this.editForm = row
        this.detailVisible = true
        this.editFormStatus = false
      },
      editSubmit (option, type) {
        let _self = this
        if (!option) {
          let data_ = {id: this.editForm.id, option: this.newObj[this.radioName]}
          console.log('提示：', data_)
          this.$post('vote/attend/id/' + this.editForm.id, data_).then((response) => {
            if (response.code === 0) {
              this.$message({
                message: '投票成功！',
                type: 'success'
              })
              _self.InitFn()
            } else {
            }
          }).catch((err) => {
            console.log(err)
          })
        }
        if (type !== 'voteCopy') {
          this.detailVisible = false
        } else {
          if (this.flag) {
            this.flag = false
            let data_ = {id: this.editForm.id, option: this.newObj[this.radioName]}
            console.log('提示：', data_)
            this.$post('vote/attend/id/' + this.editForm.id, data_).then((response) => {
              if (response.code === 0) {
                this.$message({
                  message: '投票成功！',
                  type: 'success'
                })
                this.$post('vote/edit/id/' + this.editForm.id, {}).then((response) => {
                  if (response.code === 0) {
                    let rowlist = response.vo.option
                    if (typeof rowlist !== 'string') {
                      response.vo.option = response.vo.option.join(', ')
                    }
                    this.editForm = response.vo
                    setTimeout(() => {
                      _self.flag = true
                    }, 500)
                    // _self.InitFn()
                  } else {
                  }
                }).catch((err) => {
                  console.log(err)
                })
              } else {
              }
            }).catch((err) => {
              console.log(err)
            })
          }
        }
        setTimeout(() => {
          _self.editFormStatus = true
        }, 200)
      },
      resetForm () {
        let _self = this
        this.detailVisible = false
        setTimeout(() => {
          _self.editFormStatus = true
        }, 200)
      },
      // 刷新页面
      refreshFn () {
        this.InitFn()
      },
      initFile () {
        this.InitFn()
      },
      handleDetel (index) {
        this.$confirm('确认永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.detelRespon(index)
        }).catch(() => {
        })
      },
      detelRespon (index) {
        this.$post(api.vote_delete, {id: this.arryList[index].id}).then((response) => {
          if (response.code === 0) {
            this.arryList.splice(index, 1)
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          } else {
          }
        }).catch((err) => {
          console.log(err)
        })
      }
    },
    mounted () {
    }
  }
</script>

<style lang="scss">
  #tablebox {
    display: flex;
    flex-direction: column;
  }

  .el-table {
    color: #000;
  }

  .right-box .container .main .content-container .input-val-box .input-top {
    width: 250px;
  }

</style>
